package com.microservices.controller;

import com.microservices.entity.Department;
import com.microservices.services.DepartmentServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentServices departmentServices;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getDepartmentList")
    public List<Department> getDepartmentList(){
        return departmentServices.list();
    }

    @GetMapping("/discovery")
    public List<Map<String,Object>> discover(){
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("serviceName", instance.getServiceId());
                map.put("host", instance.getHost());
                map.put("port", instance.getPort());
                map.put("uri", instance.getUri());
                list.add(map);
            }
        }
        return list;
    }


}
